#include "webviewform.h"
#include "ui_webviewform.h"
#include <QWebElementCollection>
#include <QWebFrame>
#include <QSettings>
#include <QDebug>
#include <QDate>
#include <QDateTime>

const QString USER_AGENT("Mozilla/5.0 (X11; Linux i686; rv:7.0.1) Gecko/20100101 Firefox/7.0.1");
const unsigned short stepBuyPickaxe = 30; // не знаю
const unsigned short stepBuyGoggles = 20; // не знаю
const unsigned short stepBuyHelmet = 20; // не знаю
//static unsigned short stepBuyMinePickaxe;
//static unsigned short stepBuyMineGoggles;
//static unsigned short stepBuyMineHelmet;

//---------------------------------------------------------------------------------------------------------------------
QString TunedPage::userAgentForUrl(const QUrl& /*url*/) const
{
    return USER_AGENT;
}

//---------------------------------------------------------------------------------------------------------------------
WebViewForm::WebViewForm(QWidget *parent) : QWidget(parent), ui(new Ui::WebViewForm)
{
    autoactionTimer = NULL;
    ui->setupUi(this);
    readSettings();
    initState();
    initWidget();
    createConnections();
    setupNextDayWatchdog();
}

//---------------------------------------------------------------------------------------------------------------------
WebViewForm::~WebViewForm()
{
    delete ui;
}

//---------------------------------------------------------------------------------------------------------------------
void WebViewForm::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type())
    {
        case QEvent::LanguageChange:
            ui->retranslateUi(this);
            break;
        default:
            break;
    }
}

void WebViewForm::cancelAutoaction(bool ok) {
    if (autoactionTimer) {
        if (ok) {
            qDebug() << "autoaction completed";
        } else {
            qDebug() << "autoaction cancelled";
        }
        delete autoactionTimer;
        autoactionTimer = NULL;
    }
}

void WebViewForm::GoTo(const QString& url, bool rightNow) {
    cancelAutoaction();
    if (!url.isEmpty()) {
        newLocation = tr("location.href=\"%1\";").arg(url);
    }
    qDebug() << QString("GoTo {%1}").arg(newLocation);
    if (rightNow) {
        QTimer::singleShot(0, this, SLOT(linkClick()));
        return;
    }
    int delay = 1000 + qrand() % 10000;
    autoactionTimer = new QTimer(this);
    autoactionTimer->setInterval(delay);
    autoactionTimer->setSingleShot(true);
    connect(autoactionTimer, SIGNAL(timeout()), this, SLOT(linkClick()));
    autoactionTimer->start();
}

void WebViewForm::clickButton(bool rightNow) {
    cancelAutoaction();
    if (rightNow) {
        emit QTimer::singleShot(0, this, SLOT(buttonClick()));
        return;
    }
    int delay = 1000 + qrand() % 10000;
    autoactionTimer = new QTimer(this);
    autoactionTimer->setInterval(delay);
    autoactionTimer->setSingleShot(true);
    connect(autoactionTimer, SIGNAL(timeout()), this, SLOT(buttonClick()));
    autoactionTimer->start();
}

void WebViewForm::GoToWork(const QString& defaultUrl) {
    QWebElement e = mainFrame->findFirstElement("DIV[id=rmenu1]");
    if (e.isNull()) {
        qDebug() << "??? rmenu1 not found";
        return;
    }
    e = e.findFirst("DIV.timers");
    if (e.isNull()) {
        qDebug() << "??? rmenu1 -> timers not found";
        return;
    }
    e = e.firstChild();
    if (e.tagName() != "A") {
        qDebug() << "??? first tag is not anchor";
        return;
    }
    QString href = e.attribute("href");
    if (href == "/") href = defaultUrl;
    QString  base = mainFrame->baseUrl().toString() + href;
    QString  cur = mainFrame->url().toString();
    if (base == cur) {
        qDebug () << QString("{%1} == {%2}").arg(base, cur);
    } else {
        GoTo(href);
    }

}

void WebViewForm::setupNextDayWatchdog() {
    QDateTime now = QDateTime::currentDateTime();
    QDateTime newday = QDateTime(now.date().addDays(1)).addSecs(2 * 3600 + 1);
    int seconds = now.secsTo(newday);
    qDebug() << tr("новый день настанет через %1 секунд").arg(seconds);
    QTimer::singleShot(seconds * 1000L, this, SLOT(newDay()));
}

//---------------------------------------------------------------------------------------------------------------------
void WebViewForm::readSettings()
{
    qDebug() << tr("читаем настройки...");
    QSettings settings("botva.ini", QSettings::IniFormat);
    //---------------------------------------------------
    settings.beginGroup("Profile");
    gameServer = settings.value("server").toString();
    userLogin = settings.value("login").toString();
    userPassword = settings.value("password").toString();
    settings.endGroup();
    bool ok;
    //---------------------------------------------------
    settings.beginGroup("Mine");
    minPercent = settings.value("percent").toInt(&ok);
    if (!ok)
    {
        minPercent = 50;
    }
    digInterval = settings.value("diginterval").toFloat(&ok);
    workInterval = settings.value("workinterval").toFloat(&ok);
    level = settings.value("level").toInt(&ok);
    if (!ok)
    {
        level = 0;
    }
    miner = settings.value("miner").toInt(&ok);
    if (level < 20)
    {
        miner = false;
    }
    else if (ok && miner)
    {
        buyMinePickaxe = buyMineGoggles = buyMineHelmet = true;
        miner = true;
    }
    else
    {
        miner = false;
    }
    use_MinerShopping = settings.value("shopping", true).toBool();
    use_MineWay = settings.value("mineway", false).toBool();
    settings.endGroup();
    //---------------------------------------------------
    // Добавить:
    // 1) время работы бота
    // 2) время работы шахтера
    // 3) время работы бодалки
    // 4) время работы летунов
    settings.beginGroup("Time");
    settings.endGroup();

    settings.beginGroup("Fighter");
    use_Dozor   = settings.value("dozor", true).toBool();
    use_Scares  = settings.value("scares", true).toBool();
    settings.endGroup();

    if (use_Dozor)
    {
        qDebug() << tr("мы будем ходить в дозор.");
    }
    else
    {
        qDebug() << tr("в дозор ходить не станем.");
    }
    if (use_Scares)
    {
        qDebug() << tr("мы будем задирать страшилок.");
    }
    else
    {
        qDebug() << tr("страшилок трогать не станем.");
    }
    if (use_MinerShopping)
    {
        qDebug() << tr("будем закупаться в магазине у крокодила .");
    }
    else
    {
        qDebug() << tr("шахтёрский инвентарь закупать не будем.");
    }
    if (use_MineWay)
    {
        qDebug() << tr("переходим в шахту прямо с заглавной страницы");
    }
    else
    {
        qDebug() << tr("в шахту из индексной страницы ломиться не станем");
    }
    emit log(notifyType, tr("настройки прочитаны..."));
}


//---------------------------------------------------------------------------------------------------------------------
void WebViewForm::initWidget()
{
    QNetworkAccessManager *oldManager = ui->widget->page()->networkAccessManager();
    networkAccessManager = new NetworkAccessManager(oldManager, this);
    ui->widget->page()->setNetworkAccessManager(networkAccessManager);
    page = new TunedPage(this);
    page->setNetworkAccessManager(networkAccessManager);
    ui->widget->setPage(page);
    QString url;
    url = tr("http://%1.botva.ru").arg(gameServer);
    ui->widget->setUrl(QUrl(url));
    mainFrame = page->mainFrame();

    interval = 10000;
    mineTimer = new QTimer(this);
    mineTimer->setSingleShot(true);
    connect(mineTimer, SIGNAL(timeout()), this, SLOT(mineOpen()));

    dozorMonsterTimer = new QTimer(this);
    dozorMonsterTimer->setSingleShot(true);

    harbourPierWaitTimer = new QTimer(this);
    harbourPierWaitTimer->setSingleShot(true);
}

//---------------------------------------------------------------------------------------------------------------------
void WebViewForm::initState()
{
    fishFlag = FISH_NONE;
    dozorState = DOZOR_READY;
    notifyType = NOTIFY_NONE;
}

//---------------------------------------------------------------------------------------------------------------------
void WebViewForm::createConnections()
{
    connect(ui->widget, SIGNAL(loadFinished(bool)), this, SLOT(loadFinished(bool)));
}

//---------------------------------------------------------------------------------------------------------------------
WebViewForm::PageType WebViewForm::whatIsPage()
{
    QString url;
    url = tr("http://%1.botva.ru/").arg(gameServer);
    ui->urlLabel->setText(tr("URL: %1").arg(ui->widget->url().toString()));

    if (ui->widget->url().toString() == url)
    {
//        if (ui->widget->url().path() == "/")
//        {
            return PAGE_LOGIN;
//        }
    }
    else if (ui->widget->url().toString() == "http://www.botva.ru/")
    {
        return PAGE_LOGOUT;
    }
    else if (ui->widget->url().path() == "/index.php")
    {
        return PAGE_INDEX;
    }
    else if (ui->widget->url().path() == "/mine.php")
    {
        QString actionQuery = ui->widget->url().queryItemValue("a");
        if (actionQuery == "open")
        {
            return PAGE_MINEOPEN;
        }
        else if (actionQuery == "shop")
        {
            return PAGE_MINESHOP;
        }
        return PAGE_MINE;
    }
    else if (ui->widget->url().path() == "/dozor.php")
    {
        QString actionQuery = ui->widget->url().queryItemValue("a");
        if (actionQuery == "monster")
        {
            return PAGE_DOZORMONSTER;
        }
        return PAGE_DOZOR;
    }
    else if (ui->widget->url().path() == "/fight_log.php")
    {
        return PAGE_FIGHTLOG;
    }
    else if (ui->widget->url().path() == "/harbour.php")
    {
        QString actionQuery = ui->widget->url().queryItemValue("a");
        if (actionQuery == "pier")
        {
            return PAGE_HARBOURPIER;
        }
        return PAGE_HARBOUR;
    }
    else if (ui->widget->url().path() == "/clan.php")
    {
        return PAGE_CLAN;
    }
    else if (ui->widget->url().path() == "/clan_mod.php")
    {
        QString modQuery = ui->widget->url().queryItemValue("m");
        if (modQuery == "treasury")
        {
            return PAGE_CLANTREASURY;
        }
    }
    else if (ui->widget->url().path() == "/village.php")
    {
        return PAGE_VILLAGE;
    }
    else if (ui->widget->url().path() == "/smith.php")
    {
        QString actionQuery = ui->widget->url().queryItemValue("a");
        if (actionQuery == "master")
        {
            if (ui->widget->url().queryItemValue("upgrade").isEmpty())
            {
                return PAGE_SMITHMASTER;
            }
            return PAGE_SMITHMASTERUPGRADE;
        }
        return PAGE_SMITH;
    }
    else if (ui->widget->url().path() == "/post.php")
    {
        return PAGE_POST;
    }
    else if (ui->widget->url().path() == "/shtab.php")
    {
        return PAGE_STAFF;
    }
    else if (ui->widget->url().path() == "/castle.php")
    {
        if (ui->widget->url().queryItemValue("a").contains("zoo"))
        {
            return PAGE_CASTLEZOO;
        }
        return PAGE_CASTLE;
    }
    return PAGE_NONE;
}

void WebViewForm::loadStarted()
{
    cancelAutoaction();
}

//---------------------------------------------------------------------------------------------------------------------
void WebViewForm::loadFinished(bool)
{
    QString text;
    PageType pageType;
    pageType = whatIsPage();
    switch (pageType)
    {
        case PAGE_LOGIN:
            text = "Login page loaded...";
            login();
            break;
        case PAGE_LOGOUT:
            text = "Logout page loaded...";
            logout();
            break;
        case PAGE_INDEX:
            text = "Index page loaded...";
            index();
            break;
        case PAGE_DOZOR:
            text = "Dozor page loaded...";
            checkDozor();
            break;
        case PAGE_DOZORMONSTER:
            text = "Dozor monster page loaded...";
            dozorMonster();
            break;
        case PAGE_FIGHTLOG:
            text = "Fight log page loaded...";
            fightLog();
            break;
        case PAGE_MINE:
            text = "Mine page loaded...";
//            mine();
            break;
        case PAGE_MINEOPEN:
            text = "Mine open page loaded...";
            mineOpen();
            break;
        case PAGE_MINESHOP:
            text = "Mine shop page loaded...";
            mineShop();
            break;
        case PAGE_HARBOUR:
            text = "Harbour page loaded...";
            break;
        case PAGE_HARBOURPIER:
            text = "Harbour pier page loaded...";
            harbourPier();
            break;
        case PAGE_CLAN:
            text = "Clan page loaded...";
            break;
        case PAGE_CLANTREASURY:
            text = "Clan treasury page loaded...";
            break;
        case PAGE_VILLAGE:
            text = "Vilage page loaded...";
            break;
        case PAGE_SMITH:
            text = "Smith page loaded...";
            break;
        case PAGE_SMITHMASTER:
            text = "Smith master page loaded...";
            break;
        case PAGE_SMITHMASTERUPGRADE:
            text = "Smith master upgrade page loaded...";
            break;
        case PAGE_POST:
            text = "Post page loaded...";
            break;
        case PAGE_STAFF:
            text = "Staff page loaded...";
            break;
        case PAGE_CASTLE:
            text = "Castle page loaded...";
            break;
        case PAGE_CASTLEZOO:
            text = "Castle page with zoo loaded...";
            break;
        case PAGE_NONE:
        default:
            text = tr("Неизвестная природе страница...");
            break;
    }
//    emit log(notifyType, text);
//    emit evalStateMashine(pageType);
}

//---------------------------------------------------------------------------------------------------------------------
void WebViewForm::linkClick()
{
    cancelAutoaction(true);
    mainFrame->evaluateJavaScript(newLocation);
    return;
}

//---------------------------------------------------------------------------------------------------------------------
void WebViewForm::buttonClick()
{
    cancelAutoaction(true);
    input.evaluateJavaScript("this.click()");
    return;
}

//---------------------------------------------------------------------------------------------------------------------
void WebViewForm::login()
{
    QWebElementCollection inputElements = mainFrame->findAllElements("input");
    foreach (input, inputElements)
    {
        if (input.attribute("name") == "email")
        {
            input.setAttribute("value", userLogin);
        }
        else if (input.attribute("name") == "password")
        {
            input.setAttribute("value", userPassword);
        }
        else if (input.attribute("type") == "submit")
        {
            break;
        }
    }
//    emit QTimer::singleShot(3000, this, SLOT(buttonClick()));
    clickButton();
}

//---------------------------------------------------------------------------------------------------------------------
void WebViewForm::logout()
{
    QString url;
    url = tr("http://%1.botva.ru/").arg(gameServer);
    ui->widget->setUrl(QUrl(url));
}

//---------------------------------------------------------------------------------------------------------------------
void WebViewForm::index()
{
//    test();
//    QWebElementCollection aElements = mainFrame->findAllElements("a");
//    foreach (a, aElements)
//    {
//        if (a.attribute("id") == "m6")
//        {
//            break;
//        }
//    }
//    newLocation = "location.href=\"mine.php\"";
//    emit QTimer::singleShot(3000, this, SLOT(linkClick()));
    GoToWork("mine.php?a=open");
}

//---------------------------------------------------------------------------------------------------------------------
void WebViewForm::mine()
{
//    QWebElementCollection aElements = mainFrame->findAllElements("input");
//    foreach (a, aElements)
//    {
//        if (a.attribute("href") == "mine.php?a=open")
//        {
//            break;
//        }
//    }
//    newLocation = "location.href=\"mine.php?a=open\"";
//    emit QTimer::singleShot(3000, this, SLOT(linkClick()));
}

//---------------------------------------------------------------------------------------------------------------------
void WebViewForm::mineOpen()
{
    bool ok;
    getInfo();
    if (fishFlag == FISH_READY && fishJihad > 0 && !harbourPierWaitTimer->isActive())
    {
        checkPier();
        return;
    }
    checkCastle();
    if (mineTimer->isActive())
    {
        return;
    }
    int perc;
    QUrl url(tr("http://%1.botva.ru/").arg(gameServer));
    QString str;
    QWebElement a, td;
    QWebElementCollection divElements, aElements;
    divElements = mainFrame->findAllElements("div");
    foreach (a, divElements)
    {
        if (a.hasAttribute("class"))
        {
            if (a.attribute("class") == "grbody")
            {
                QWebElementCollection pElements = a.findAll("p");
                if (pElements.count())
                {
                    QString info(pElements[0].toPlainText().remove(QChar('\n')));
                    // XXX: может нужно будет выводить инфу
                    QRegExp rx1("([\\d]+) %");
                    if (rx1.indexIn(info) != -1)
                    {
                        perc = rx1.cap(1).toInt(&ok);
    //                    if (!ok) { qDebug() << "dig percent: " << perc; }
                        break;
                    }
                }
            }
            else if (a.attribute("class") == "message")
            {
                // Позже можно разобрать строчку, чтоб потом в картинках можно было получать
                // (кристаллы, ББП, БМП, релики)
                QString text(a.toPlainText().remove(QChar('\n')));
//                text = a.toPlainText();
//                QString text2;
//                text2 = a.toOuterXml();
                emit log(notifyType, text);
//                emit log(notifyType, text2);
            }
        }
    }
    bool dig = false;
    aElements = mainFrame->findAllElements("a");
    foreach (a, aElements)
    {
        if (a.hasAttribute("href") && a.attribute("href").indexOf("mine.php?a=open") != -1)
        {
            str = a.attribute("href");
            url.setPath(str);
            if (str.indexOf("m=dig") != -1)
            {
                // TODO: Добавить вывод информации о произошедшем действии
                if (perc >= minPercent)
                {
//                    newLocation = tr("location.href=\"%1\"").arg(str);
//                    emit QTimer::singleShot(0, this, SLOT(linkClick()));
                    GoTo(str);
                    dig = true;
                    interval = 30000 + qrand() % (int)digInterval;
                    mineTimer->setInterval(interval);
                    mineTimer->start();
                    notifyType = NOTIFY_NONE;
                    emit log(notifyType, tr("dig: interval = %1, percent = %2").arg(interval).arg(perc));
                }
            }
            else if (str.indexOf("m=reset") != -1 && !dig)
            {
                // TODO: Добавить вывод информации о произошедшем действии
//                newLocation = tr("location.href=\"%1\"").arg(str);
//                emit QTimer::singleShot(0, this, SLOT(linkClick()));
                GoTo(str);
                interval = 300000 + (float)qrand()/RAND_MAX*workInterval;
                mineTimer->setInterval(interval);
                mineTimer->start();
                notifyType = NOTIFY_NONE;
                emit log(notifyType, tr("reset: interval = %1, percent = %2").arg(interval).arg(perc));
            }
            else if (str.indexOf("m=work") != -1)
            {
                divElements = mainFrame->findAllElements("img");
                QRegExp rx("([\\d]+)");
                foreach (a, divElements)
                {
                    if (!miner)
                    {
                        if (a.attribute("src").contains("Mine_1s.jpg"))
                        {
                            td = a.parent().parent().nextSibling().firstChild();
                            if (rx.indexIn(td.toPlainText()) != -1)
                            {
                                pickaxe = rx.cap(1).toInt(&ok);
                //                if (ok) { qDebug() << "mP: " << minePickaxe; }
                            }
                        }
                        else if (a.attribute("src").contains("Mine_2s.jpg"))
                        {
                            td = a.parent().parent().nextSibling().firstChild();
                            if (rx.indexIn(td.toPlainText()) != -1)
                            {
                                goggles = rx.cap(1).toInt(&ok);
                //                if (ok) { qDebug() << "mG: " << mineGoggles; }
                            }
                        }
                        else if (a.attribute("src").contains("Mine_3s.jpg"))
                        {
                            td = a.parent().parent().nextSibling().firstChild();
                            if (rx.indexIn(td.toPlainText()) != -1)
                            {
                                helmet = rx.cap(1).toInt(&ok);
                //                if (ok) { qDebug() << "mH: " << mineHelmet; }
                            }
                        }
                    }
                    else // miner
                    {
                        if (a.attribute("src").contains("Mine_4s.jpg"))
                        {
                            td = a.parent().parent().nextSibling().firstChild();
                            if (rx.indexIn(td.toPlainText()) != -1)
                            {
                                minePickaxe = rx.cap(1).toInt(&ok);
                //                if (ok) { qDebug() << "mP: " << minePickaxe; }
                            }
                        }
                        else if (a.attribute("src").contains("Mine_5s.jpg"))
                        {
                            td = a.parent().parent().nextSibling().firstChild();
                            if (rx.indexIn(td.toPlainText()) != -1)
                            {
                                mineGoggles = rx.cap(1).toInt(&ok);
                //                if (ok) { qDebug() << "mG: " << mineGoggles; }
                            }
                        }
                        else if (a.attribute("src").contains("Mine_6s.jpg"))
                        {
                            td = a.parent().parent().nextSibling().firstChild();
                            if (rx.indexIn(td.toPlainText()) != -1)
                            {
                                mineHelmet = rx.cap(1).toInt(&ok);
                //                if (ok) { qDebug() << "mH: " << mineHelmet; }
                            }
                        }
                    }
                }
                if (use_MinerShopping)
                {
                    buyMinePickaxe = buyMineGoggles = buyMineHelmet = buyPickaxe = buyGoggles = buyHelmet = false;
                    if (!miner)
                    {
                        if (pickaxe <= 30 && gold >= 10000)
                        {
                            buyPickaxe = true;
                        }
                        if (goggles <= 20 && gold >= 6000)
                        {
                            buyGoggles = true;
                        }
                        if (helmet <= 20 && gold >= 6000)
                        {
                            buyHelmet = true;
                        }
                        if (buyPickaxe || buyGoggles || buyHelmet)
                        {
                            notifyType = NOTIFY_NONE;
                            emit log(notifyType, tr("Можно докупить инструмента. Кирка: %1, очки: %2, каска: %3.")
                                     .arg(45 - pickaxe).arg(30 - goggles).arg(30 - helmet));
                            newLocation = "location.href=\"/mine.php?a=shop\"";
                            emit QTimer::singleShot(3000, this, SLOT(linkClick()));
                            return;
                        }
                    }
                    else // if miner
                    {
                        if (minePickaxe <= level*2 && gold >= 10000)
                        {
                            buyMinePickaxe = true;
                        }
                        if (mineGoggles <= level*2 &&
                            gold >= (buyMinePickaxe ? 10000 : 0) + 6000)
                        {
                            buyMineGoggles = true;
                        }
                        if (mineHelmet <= level*2 &&
                            gold >= (buyMinePickaxe ? 10000 : 0) + (buyMineGoggles ? 6000 : 0) + 6000)
                        {
                            buyMineHelmet = true;
                        }
                        if (buyMinePickaxe || buyMineGoggles || buyMineHelmet)
                        {
                            notifyType = NOTIFY_NONE;
                            // сообщение расширим
                            emit log(notifyType, tr("Можно докупить крутого инструмента. Кирка: %1, очки: %2, каска: %3.")
                                     .arg(buyMinePickaxe ? level*3 - minePickaxe : 0)
                                     .arg(buyMineGoggles ? level*3 - mineGoggles : 0)
                                     .arg(buyMineHelmet  ? level*3 - mineHelmet  : 0));
                            newLocation = "location.href=\"/mine.php?a=shop\"";
                            emit QTimer::singleShot(3000, this, SLOT(linkClick()));
                            return;
                        }
                    }
                }
                if (!dozorMonsterTimer->isActive() && (use_Dozor || use_Scares))
                {
                    if (dozorState == DOZOR_READY || dozorState == DOZOR_MONSTER)
                    {
//                        newLocation = "location.href=\"dozor.php\"";
//                        emit QTimer::singleShot(3000, this, SLOT(linkClick()));
                        GoTo("dozor.php");
                        return;
                    }
                }

                // TODO: Добавить вывод информации о произошедшем действии
//                newLocation = tr("location.href=\"%1\"").arg(str);
//                emit QTimer::singleShot(0, this, SLOT(linkClick()));
                GoTo(str);

                interval = 300000 + (float)qrand()/RAND_MAX*workInterval;
                mineTimer->setInterval(interval);
                mineTimer->start();

//                notifyType = NOTIFY_NONE;
//                emit log(notifyType, tr("work: interval = %1").arg(interval));
            }
        }
    }
}

//---------------------------------------------------------------------------------------------------------------------
void WebViewForm::mineShop()
{
    getInfo();
    if (!use_MinerShopping)
    {
        emit log(notifyType, QString("[Miner]shopping=false"));
//        newLocation = "location.href=\"mine.php?a=open\"";
//        emit QTimer::singleShot(2000 + qrand() % 10000, this, SLOT(linkClick()));
        GoTo("mine.php?a=open");
        return;
    }
    if (miner)
    {
        if (minePickaxe > level*2 && mineGoggles > level*2 && mineHelmet > level*2)
        {
//            newLocation = "location.href=\"mine.php?a=open\"";
//            emit QTimer::singleShot(2000 + qrand() % 10000, this, SLOT(linkClick()));
            GoTo("mine.php?a=open");
            return;
        }
    }
    else // !miner
    {
        if (pickaxe > 30 && goggles > 20 && helmet > 20)
        {
//            newLocation = "location.href=\"mine.php?a=open\"";
//            emit QTimer::singleShot(2000 + qrand() % 10000, this, SLOT(linkClick()));
            GoTo("mine.php?a=open");
            return;
        }
    }
    QWebElement localInput;
    QWebElementCollection inputElements = mainFrame->findAllElements("input");
    bool needClickBuy = false;
    QString buyTamplate("$(\"#slider_v_%1\").val(%2 + '')");
    foreach (localInput, inputElements)
    {
        if (!miner)
        {
            if (localInput.attribute("id") == "slider_1" && pickaxe <= 30)
            {
                localInput.evaluateJavaScript("$(\"#slider_v_1\").val(15 + '')");
                localInput.evaluateJavaScript("$(\"#slider_1\").slider(\"value\",this.value)");
                needClickBuy = true;
            }
            else if (localInput.attribute("id") == "slider_v_2" && goggles <= 20)
            {
                localInput.evaluateJavaScript("$(\"#slider_v_2\").val(10 + '')");
                localInput.evaluateJavaScript("$(\"#slider_2\").slider(\"value\",this.value)");
                needClickBuy = true;
            }
            else if (localInput.attribute("id") == "slider_v_3" && helmet <= 20)
            {
                localInput.evaluateJavaScript("$(\"#slider_v_3\").val(10 + '')");
                localInput.evaluateJavaScript("$(\"#slider_3\").slider(\"value\",this.value)");
                needClickBuy = true;
            }
        }
        else // miner
        {
            if (localInput.attribute("id") == "slider_v_4" && buyMinePickaxe)
            {
                localInput.evaluateJavaScript(buyTamplate.arg("4").arg(level));
                localInput.evaluateJavaScript("$(\"#slider_4\").slider(\"value\",this.value)");
                needClickBuy = true;
            }
            else if (localInput.attribute("id") == "slider_v_5" && buyMineGoggles)
            {
                localInput.evaluateJavaScript(buyTamplate.arg("5").arg(level));
                localInput.evaluateJavaScript("$(\"#slider_5\").slider(\"value\",this.value)");
                needClickBuy = true;
            }
            else if (localInput.attribute("id") == "slider_v_6" && buyMineHelmet)
            {
                localInput.evaluateJavaScript(buyTamplate.arg("6").arg(level));
                localInput.evaluateJavaScript("$(\"#slider_6\").slider(\"value\",this.value)");
                needClickBuy = true;
            }
            else if (localInput.attribute("type") == "submit" &&
                     localInput.attribute("value") == tr("КУПИТЬ"))
            {
                input = localInput;
            }
        }
    }
    if (needClickBuy)
    {
        if (miner)
        {
            minePickaxe += level;
            mineGoggles += level;
            mineHelmet  += level;
        }
        else // !miner
        {
            pickaxe += 30;
            goggles += 20;
            helmet  += 20;
        }
        emit log(notifyType, tr("закупаем набранный шмут"));
//        emit QTimer::singleShot(3000, this, SLOT(buttonClick()));
        clickButton();
    }
    return;
}

//---------------------------------------------------------------------------------------------------------------------
void WebViewForm::checkPier()
{
//    newLocation = "location.href=\"/harbour.php?a=pier\"";
//    emit QTimer::singleShot(3000, this, SLOT(linkClick()));
    GoTo("harbour.php?a=pier");
}

//---------------------------------------------------------------------------------------------------------------------
void WebViewForm::harbourPier()
{
    if (fishJihad < 5 && crystal > 71)
    {
        // TODO: Добавить покупку лодок
        emit log(notifyType, tr("Можно докупить корабликов!"));
    }
    if (fishFlag == FISH_READY && fishJihad > 0)
    {
        QWebElementCollection inputElements = mainFrame->findAllElements("input");
        foreach (input, inputElements)
        {
            if (input.attribute("value") == tr("ОТПРАВИТЬ"))
            {
                emit log(notifyType, tr("Можно поплавать. Осталось походов: %1").arg(fishJihad));
//                emit QTimer::singleShot(3000, this, SLOT(buttonClick()));
                clickButton();
                fishFlag = FISH_DO;
                break;
            }
        }
        if (fishFlag != FISH_DO)
        {
//            emit QTimer::singleShot(20000, this, SLOT(checkPier()));
            harbourPierWaitTimer->start(90000);
//            newLocation = "location.href=\"mine.php?a=open\"";
//            emit QTimer::singleShot(3000, this, SLOT(linkClick()));
            GoTo("mine.php?a=open");
//            notifyType = NOTIFY_NONE;
//            emit log(notifyType, "habour pier: wait for board");
        }
    }
    else if (fishFlag == FISH_DO)
    {
//        newLocation = "location.href=\"mine.php?a=open\"";
//        emit QTimer::singleShot(3000, this, SLOT(linkClick()));
        GoTo("mine.php?a=open");
    }
    else
    {
        ;
    }
}

//---------------------------------------------------------------------------------------------------------------------
void WebViewForm::checkDozor()
{
    QWebElementCollection inputElements;
    bool ok;

    getInfo();
    inputElements = mainFrame->findAllElements("input");
    foreach (input, inputElements)
    {
        if (input.attribute("value") == tr("НАЧАТЬ"))
        {
            QWebElement pElement;
            QWebElementCollection pElements;
            pElements = input.parent().parent().findAll("p");
            QRegExp rx(tr("([\\d]+)"));
            foreach (pElement, pElements)
            {
                if (rx.indexIn(pElement.toPlainText()) != -1)
                {
                    if (pElement.firstChild().isNull())
                    {
                        int dozorTime;
                        dozorTime = rx.cap(1).toInt(&ok);
                        rx.cap(1).toInt(&ok);
                        if (ok && dozorTime > 0)
                        {
                            dozorState = DOZOR_READY;
                            break;
                        }
                    }
                    else
                    {
                        dozorState = DOZOR_DO;
                    }
                }
            }
            if (dozorState == DOZOR_READY && use_Dozor)
            {
                // сперва посмотрим, можем ли мы вообще в дозор пойти
                if (mainFrame->findFirstElement("SELECT[id=auto_watch]")
                        .findAll("OPTION").count() == 0) {
                    emit log(notifyType,
                             tr("дозор уже исхожен, идём на шахту."));
                    dozorState = DOZOR_NONE;
                    GoTo("mine.php?a=open");
                    return;
                }
                emit log(notifyType, tr("идём в дозор."));
//                emit QTimer::singleShot(1000, this, SLOT(buttonClick()));
                clickButton();
                return;
            }
        }
        else if (use_Scares && input.attribute("value") == tr("ИСКАТЬ") && crystal > 0)
        {
            emit log(notifyType, tr("будем драться со страшилкой."));
            dozorState = DOZOR_MONSTER;
//            emit QTimer::singleShot(3000, this, SLOT(buttonClick()));
            clickButton();
            return;
        }
    }
    // я надеюсь, сюда мы не попадем
    if (dozorState == DOZOR_MONSTER)
    {
//        newLocation = "location.href=\"mine.php?a=open\"";
//        emit QTimer::singleShot(3000, this, SLOT(linkClick()));
        GoTo("mine.php?a=open");
    }
    return;
}

void WebViewForm::dozor()
{
}

void WebViewForm::dozorMonster()
{
    QWebElement form;
    QWebElementCollection formElements, inputElements;

    formElements = mainFrame->findAllElements("form");
    foreach (form, formElements)
    {
        if (form.attribute("action") == "?a=attack")
        {
            inputElements = form.findAll("input");
            foreach (input, inputElements)
            {
                if (input.attribute("type") == "submit" &&
                    input.attribute("value") == tr("НАПАСТЬ"))
                {
                    dozorMonsterTimer->start(15*60000+5000);
//                    emit QTimer::singleShot(3000, this, SLOT(buttonClick()));
                    clickButton();
                    return;
                }
            }
        }
    }
}

//---------------------------------------------------------------------------------------------------------------------
void WebViewForm::fightLog()
{
    // XXX: заглушка на охоту на страшилок
    if (dozorState == DOZOR_MONSTER)
    {
        dozorState = DOZOR_READY;
//        newLocation = "location.href=\"mine.php?a=open\"";
//        emit QTimer::singleShot(5000, this, SLOT(linkClick()));
        GoTo("mine.php?a=open");
    }
}

//---------------------------------------------------------------------------------------------------------------------
void WebViewForm::farm()
{
}

//---------------------------------------------------------------------------------------------------------------------
void WebViewForm::shop()
{
}

//---------------------------------------------------------------------------------------------------------------------
void WebViewForm::house()
{
}

//---------------------------------------------------------------------------------------------------------------------
void WebViewForm::training()
{
}

//---------------------------------------------------------------------------------------------------------------------
void WebViewForm::village()
{
}

//---------------------------------------------------------------------------------------------------------------------
void WebViewForm::witch()
{
}

//---------------------------------------------------------------------------------------------------------------------
void WebViewForm::post()
{
}

//---------------------------------------------------------------------------------------------------------------------
void WebViewForm::staff()
{
}

//---------------------------------------------------------------------------------------------------------------------
void WebViewForm::smith()
{
}

//---------------------------------------------------------------------------------------------------------------------
void WebViewForm::checkCastle()
{
    castle();
}

//---------------------------------------------------------------------------------------------------------------------
void WebViewForm::castle()
{
}

//---------------------------------------------------------------------------------------------------------------------
void WebViewForm::getInfo()
{
    bool ok;
    QString str;
    QWebElement div, li, span, b;
    QWebElementCollection divElements = mainFrame->findAllElements("div");
    foreach (div, divElements)
    {
        if (div.hasAttribute("class"))
        {
            if (div.attribute("class") == "flyings")
            {
                QWebElementCollection bElements = div.findAll("b");
                foreach (b, bElements)
                {
                    if (b.classes().contains("flying_13") != -1 && div.attribute("class") == "title")
                    {
                        emit log(notifyType, tr("Нашел %1").arg(b.attribute("title")));
                    }
                    else if (b.classes().contains("flying_23") != -1 && div.attribute("class") == "title")
                    {
                        emit log(notifyType, tr("Нашел %1").arg(b.attribute("title")));
                    }
                    else if (b.classes().contains("flying_33") != -1 && div.attribute("class") == "title")
                    {
                        emit log(notifyType, tr("Нашел %1").arg(b.attribute("title")));
                    }
                    else if (b.classes().contains("flying_43") != -1 && div.attribute("class") == "title")
                    {
                        emit log(notifyType, tr("Нашел %1").arg(b.attribute("title")));
                    }
                }
            }
            else if (div.attribute("class") == "counters")
            {
                QWebElementCollection liElements = div.findAll("li");
                foreach (li, liElements)
                {
                    if (li.attribute("title") == tr("Время до возвращения судна с пирашками"))
                    {
                        QString fishInfo;
                        span = li.findFirst("span");
                        fishInfo = span.toPlainText();
//                        qDebug() << "fish: " << fishInfo;
                        if (fishInfo == tr("00:00:00"))
                        {
                            fishFlag = FISH_READY;
                            break;
                        }
                    }
                }
            }
            else if (div.attribute("class") == "resources")
            {
                QWebElementCollection liElements = div.findAll("li");
                foreach (li, liElements)
                {
                    if (li.attribute("id") == "i39")
                    {
                        fishJihad = li.toPlainText().toInt();
                    }
                    else if (li.attribute("id") == "i23")
                    {
                        boats = li.toPlainText().toInt();
                    }
                    else if (li.attribute("id") == "i33")
                    {
                        smallGlade = li.toPlainText().toInt();
                    }
                    else if (li.attribute("id") == "i34")
                    {
                        bigGlade = li.toPlainText().toInt();
                    }
                }
            }
            else if (div.attribute("class") == "char_stat")
            {
                if (div.attribute("id") == "char")
                {
//                    int current_health, max_health, regen_health;
//                    str = div.attribute("onMouseOver");
//                    QRegExp rx("\\D+([\\d]+)\\D+([\\d]+)\\D+([\\d]+)");
//                    if (rx.indexIn(str) != -1)
//                    {
//                        current_health = rx.cap(1).toInt(&ok);
//                        max_health = rx.cap(2).toInt(&ok);
//                        regen_health = rx.cap(3).toInt(&ok);
//                    }
//                    emit log(notifyType, tr("char health: current - %1, max - %2, regen - %3").arg(current_health).arg(max_health).arg(regen_health));
//                    QWebElement a = div.findFirst("a");
//                    emit log(notifyType, tr("char drink: %1").arg(a.attribute("href")));
                }
                if (div.attribute("id") == "pet")
                {
//                    int notifyType = 0;
//                    QWebElement a = div.findFirst("a");
//                    emit log(notifyType, tr("pet do cage: %1").arg(a.attribute("href")));
//                    a = div.findFirst("div");
//                    emit log(notifyType, tr("pet health: %1").arg(a.attribute("onMouseOver")));
                }
            }
            else if (div.attribute("class") == "money")
            {
                // TODO парсить: safe, safe_add, pandora, safe3, free
                if (div.attribute("id") == "gold")
                {
                    str = div.attribute("onMouseOver");
                    QRegExp rx("([\\d]+)");
                    if (rx.indexIn(str, 25) != -1)
                    {
                        gold = rx.cap(1).toInt(&ok);
                        if (!ok)
                        {
                            gold = -1;
                        }
                    }
                }
                if (div.attribute("id") == "crystal")
                {
                    // TODO парсить: safe, free
                    str = div.attribute("onMouseOver");
                    QRegExp rx("([\\d]+)");
                    if (rx.indexIn(str, 25) != -1)
                    {
                        crystal = rx.cap(1).toInt(&ok);
                        if (!ok)
                        {
                            crystal = -1;
                        }
                    }
                }
                if (div.attribute("id") == "fish")
                {
                    str = div.toPlainText();
                    str.remove(QChar('.'));
                    QRegExp rx("([\\d]+)");
                    if (rx.indexIn(str) != -1)
                    {
                        piranhas = rx.cap(1).toInt(&ok);
                        if (!ok)
                        {
                            piranhas = -1;
                        }
                    }
                }
                if (div.attribute("id") == "green")
                {
                    // зелень
                }
            }
        }
    }
//    if (gold != -1 && crystal != -1 && piranhas != -1)
//    {
//        emit log(notifyType, tr("gold: %1, crystal: %2, piranhas: %3").arg(gold).arg(crystal).arg(piranhas));
//    }
}

//=====================================================================================================================
void WebViewForm::test()
{
    QWebElement div, li, span;
    QWebElementCollection divElements = mainFrame->findAllElements("div");
    foreach (div, divElements)
    {
        if (div.hasAttribute("class"))
        {
            if (div.attribute("class") == "timers")
            {
                QWebElementCollection spanElements = div.findAll("span");
                foreach (span, spanElements)
                {
                    if (span.attribute("id") == "counter_12")
                    {
                        qDebug() << "Mine: " << span.toPlainText();
                    }
                }
            }
            else if (div.attribute("class") == "resources")
            {
                QWebElementCollection liElements = div.findAll("li");
                foreach (li, liElements)
                {
                    if (li.attribute("id") == "i16")
                    {
                        qDebug() << "r1: " << li.toPlainText();
                    }
                    else if (li.attribute("id") == "i17")
                    {
                        qDebug() << "r2: " << li.toPlainText();
                    }
                    else if (li.attribute("id") == "i18")
                    {
                        qDebug() << "r3: " << li.toPlainText();
                    }
                    else if (li.attribute("id") == "i33")
                    {
                        qDebug() << "r4: " << li.toPlainText();
                    }
                    else if (li.attribute("id") == "i34")
                    {
                        qDebug() << "r5: " << li.toPlainText();
                    }
                    else if (li.attribute("id") == "i39")
                    {
                        qDebug() << "r6: " << li.toPlainText();
                    }
                }
            }
            else if (div.attribute("class") == "counters")
            {
                QWebElementCollection liElements = div.findAll("li");
                foreach (li, liElements)
                {
                    if (li.attribute("title") == tr("Время активации Сейфа"))
                    {
                        span = li.findFirst("span");
                        qDebug() << "safe: " << span.toPlainText();
                    }
                    else if (li.attribute("title") == tr("Время активации Кристального Сейфа"))
                    {
                        span = li.findFirst("span");
                        qDebug() << "cristal safe: " << span.toPlainText();
                    }
                    else if (li.attribute("title") == tr("Время до возвращения судна с пирашками"))
                    {
                        span = li.findFirst("span");
                        qDebug() << "fish: " << span.toPlainText();
                    }
                }
            }
            else if (div.attribute("class") == "char_stat")
            {
                qDebug() << "health: " << div.attribute("onMouseOver");
                QWebElement a = div.findFirst("a");
                qDebug() << "drink: " << a.attribute("href");
            }
            else if (div.attribute("class") == "money")
            {
                if (div.attribute("id") == "gold")
                {
                    qDebug() << "gold: " << div.attribute("onMouseOver");
                }
                else if (div.attribute("id") == "crystal")
                {
                    qDebug() << "crystal: " << div.attribute("onMouseOver");
                }
                else if (div.attribute("id") == "fish")
                {
                    qDebug() << "fish: " << div.toPlainText();
                }
            }
        }
    }
}


void WebViewForm::newDay() {
    emit log(notifyType, tr("--- new day started!"));
    if (dozorState == DOZOR_NONE) {
        dozorState = DOZOR_READY;
    }
    setupNextDayWatchdog();
}
